package lspay

import (
	"encoding/json"

	"codeup.aliyun.com/5f9118049cffa29cfdd3be1c/util/cipher/payserver"
)

type AllReq struct {
	BizParams string `json:"bizParams"`
	AesKey    string `json:"aesKey"`
}

// Bytes 获取请求参数
func (p *AllReq) Bytes() []byte {
	bs, _ := json.Marshal(p)
	return bs
}

type AllResp struct {
	BizParams string `json:"bizParams"`
	AesKey    string `json:"aesKey"`
}

func (p *AllResp) ParseRefundResponse(privateKey string) (*RefundResponse, error) {
	bs, err := getPayCenterResponse(p.AesKey, privateKey, p.BizParams)
	if err != nil {
		return nil, err
	}

	var refundResp *RefundResponse
	if err = json.Unmarshal(bs, &refundResp); err != nil {
		return nil, err
	}
	return refundResp, nil
}

func (p *AllResp) ParsePayResponse(privateKey string) (*PayResponse, error) {
	bs, err := getPayCenterResponse(p.AesKey, privateKey, p.BizParams)
	if err != nil {
		return nil, err
	}

	var payResp *PayResponse
	if err = json.Unmarshal(bs, &payResp); err != nil {
		return nil, err
	}
	return payResp, nil
}

func (p *AllResp) ParseCloseResponse(privateKey string) (*CloseResponse, error) {
	bs, err := getPayCenterResponse(p.AesKey, privateKey, p.BizParams)
	if err != nil {
		return nil, err
	}

	var closeResp *CloseResponse
	if err = json.Unmarshal(bs, &closeResp); err != nil {
		return nil, err
	}
	return closeResp, nil
}

func (p *AllResp) ParseQueryResponse(privateKey string) (*MerchantGetOrderReply, error) {
	bs, err := getPayCenterResponse(p.AesKey, privateKey, p.BizParams)
	if err != nil {
		return nil, err
	}

	var orderResp *MerchantGetOrderReply
	if err = json.Unmarshal(bs, &orderResp); err != nil {
		return nil, err
	}
	return orderResp, nil
}

func (p *AllReq) ParseCallbackResponse(privateKey string) (*PayCallbackRequest, error) {
	bs, err := getPayCenterResponse(p.AesKey, privateKey, p.BizParams)
	if err != nil {
		return nil, err
	}

	var callbackReq *PayCallbackRequest
	if err = json.Unmarshal(bs, &callbackReq); err != nil {
		return nil, err
	}
	return callbackReq, nil
}

// getPayCenterResponse 获取支付中心响应参数
func getPayCenterResponse(aesKey, privateKey, bizParams string) ([]byte, error) {
	passePrivily, err := payserver.ParsePrivateKey(privateKey)
	if err != nil {
		return nil, err
	}
	rsaDecrypt, err := payserver.NewRSA(payserver.WithPrivateKey(passePrivily))
	if err != nil {
		return nil, err
	}

	deAesKey, err := rsaDecrypt.Decrypt([]byte(aesKey))
	if err != nil {
		return nil, err
	}

	aesDecrypt, err := payserver.NewAesECB(payserver.WithAesECBKey(string(deAesKey)))
	if err != nil {
		return nil, err
	}

	decryptBizParams, err := aesDecrypt.Decrypt([]byte(bizParams))
	if err != nil {
		return nil, err
	}

	return decryptBizParams, nil
}
